<?php
if (! defined ( 'IN_BIC' )) {
    die ( '非法分配器访问来源!' );
}
class Bic_Core_Dispatch extends Bic_Base{

    /**
     * 路由类型,分2类：
     * 	1|normal	:普通型。
     * 		不用开启重写。但会带个问号"?",入口文件，默认为index.php（以服务器设定为准）。
     * 		url原型如：
     * 		http://example.com/？controller/action/param1/param2/param3
     * 	2|rewrite	:重写型。
     * 		必须开启重写的支持。
     * 		url原型如：
     * 		http://example.com/controller/action/param1/param2/param3
     * @var string
     */
    private static $_type = 'normal';

    public static $_routes = array();
    
    /**
     * 当前路由
     * @var array
     */
    public static $_currentRoute = null;
    
    private static $_currentController = null;
    private static $_currentAction = null;
    
    private static $_matchRoute = null;
    
    /**
     * URL中的参数队列
     * @var array
     */
    private static $_params =  array();
    
    /**
     * 是否已经添加过默认路由
     * @var bool
     */
    private static $_addDefaultRoutesed = false;
    
    /**
     * 默认控制器
     * @var string
     */
    public static $_defaultController = 'index';
    public static $_defaultAction = 'display';
    
    public static $_url = null;
    public static $_urlDelimiter = '/';
    public static $_urlVariable = ':';
    
    public static $_prefix = null;
    public static $_suffix = null;
    
    public static $_debug = false;
    

    public function __construct($router,$default=array(),$reg=array()){
        self::addRoute($router,$default,$reg);
    }

    public static function addRoute($router,$default=array(),$reg=array()){
        self::$_matchRoute = array($router,$default,$reg);
        $pattern = str_replace(
                    	'/',
                    	'\\'.self::$_urlDelimiter,
                        preg_replace_callback("/".(self::$_urlVariable)."(\w+)/i",'Bic_Router::matchReg',trim($router,self::$_urlDelimiter))
                    );
        $pattern = '[\/]{0,1}'.$pattern;
        self::$_routes[] = array($router,$default,$reg,'pattern'=>$pattern,'params'=>self::$_params);
        self::$_params=array();
        return self::$_routes;
    }
    
    /**
     * 获取已注册的所有路由
     */
    public static function getRoutes(){
        return self::$_routes;
    }
    
    /**
     * 返回当前匹配的路由
     * @param string $uri	HTTP uri 信息
     */
    public static function getCurrentRoute($uri=null){
        if (!$uri){
            $http = new Bic_Request_Http();
            $uri = $http->getRequestUri();
        }
        
        /**
         * 匹配路由器
         * 	返回匹配的路由器的索引
         * @var string
         */
        $route_index = self::match($uri);
        
        if(self::$_debug){
            So(self::$_currentRoute);
            So(self::$_params);
        }
        
        //返回当前匹配的路由器
        return self::$_routes[$route_index];
    }

    /**
     * 匹配路由
     * @param string $uri
     */
    private static function match($uri){
        if (strpos($uri,'?') !== false){
            $uris = explode('?',$uri);
            $uri = $uris[1];
        }else if('normal' == self::$_type){
            $uri= '';
        }
        
        $uri = self::$_urlDelimiter.str_replace('.html','',trim($uri,self::$_urlDelimiter));
        
        $routes = self::getRoutes();    //$router,self::$_urlDelimiter

        foreach ($routes as $routes_key => $routes_val){
            //$pattern = str_replace('/','\\'.self::$_urlDelimiter,preg_replace_callback("/".(self::$_urlVariable)."(\w+)/i",'Bic_Router::matchReg',$routes_val[0]));

            //So($routes_val['pattern']);
            //So($uri);
            if(preg_match("/^{$routes_val['pattern']}$/i",urldecode($uri),$result)){
                //参数
                if (count($result)>1){
                    for($i=1;$i<count($result);$i++){
                        $params[$routes_val['params'][$i-1]] = $result[$i];
                    }
                    self::$_params = $params;
                }
                $uri_arr = explode(self::$_urlDelimiter,$uri);
                if(empty($routes_val[1]['controller'])){
                    $routes_val[1]['controller'] = empty(self::$_params['controller']) ? (self::$_defaultController) : (self::$_params['controller']);
                }
                if(empty($routes_val[1]['action'])){
                    $routes_val[1]['action'] = empty(self::$_params['action']) ? self::$_defaultAction : self::$_params['action'];
                }
                
                /**
                 * 设置当前路由
                 */
                self::$_currentRoute = $routes_val;
                
                self::$_currentController = $routes_val[1]['controller'];
                self::$_currentAction = $routes_val[1]['action'];
                
                /**
                 * 返回当前路由索引
                 */
                return $routes_key;
            }
            
            self::$_params = array();
        }
    }
    
    static function matchReg($regs){
        self::$_params[] = $regs[1];
        
        if(!empty(self::$_matchRoute[2][$regs[1]])){
            return $reg = '('.rtrim(ltrim(self::$_matchRoute[2][$regs[1]],'('),')').')';
        }
        
        return '(\w+)';
    }
    
    /**
     * 默认路由
     */
    public static function addDefaultRoutes(){
        if(!self::$_addDefaultRoutesed){
            //添加默认路由
            self::addRoute(":controller/:action/:param",array(),array('param'=>'([1-9][0-9]*)'));
            self::$_addDefaultRoutesed = true;
        }
    }
    
    /**
     * 当前控制器
     * @return string
     */
    public static function getCurrentController(){
        if (self::$_currentController){
            return self::$_currentController;
        }else{
            throw new Bic_Exception('Router error:Loading Controller fault!');
        }
    }
    
    /**
     * 当前动作
     * @return unknown_type
     */
    public static function getCurrentAction(){
        if (self::$_currentAction){
            return self::$_currentAction;
        }else{
            throw new Bic_Exception('Router error:Loading Action fault!');
        }
    }
    
    public static function getParams(){
        return self::$_params;
    }
    
    public function writeUrl(){}

    public function getType(){
        return self::$_type;
    }
    
    public function setType($t){
        if($t=='normal' || $t=='rewrite'){
            self::$_type=$t;
        }else{
            throw new Bic_Exception('路由类型设置出错！');
        }
    }
    
	/**
	 * 设置url后缀
	 * @param string $suffix
	 */
	public static function setSuffix($suffix=null) {
	    if($suffix && strpos($suffix,'.') !== false){
		    return self::$_suffix=$suffix;
	    }
	}
}
